'use client'

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Trophy, Clock, Zap, Star, Medal, Crown, Target, Users } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { useRouter } from 'next/navigation'
interface Challenge {
  id: string
  title: string
  description: string
  difficulty: number
  timeLimit: number
  questionCount: number
  points: number
  participants: number
  topScore: number
  status: 'active' | 'completed' | 'locked'
  icon: string
}

interface UserStats {
  totalChallenges: number
  completedChallenges: number
  totalPoints: number
  rank: number
  bestStreak: number
}

export default function ChallengePage() {
  const [challenges, setChallenges] = useState<Challenge[]>([])
  const [userStats, setUserStats] = useState<UserStats | null>(null)
  const [selectedDifficulty, setSelectedDifficulty] = useState<number | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')
  const router = useRouter()


  useEffect(() => {
    loadChallenges()
    loadUserStats()
  }, [])

  const loadChallenges = async () => {
    try {
      setIsLoading(true)

      // 使用简化的挑战列表（基于难度）
      const simplifiedChallenges: Challenge[] = [
        {
          id: 'beginner-challenge',
          title: '入门挑战',
          description: '适合初学者的基础题目（1-2星难度）',
          difficulty: 1,
          timeLimit: 600,
          questionCount: 10,
          points: 100,
          participants: 0,
          topScore: 0,
          status: 'active',
          icon: '🌟'
        },
        {
          id: 'intermediate-challenge',
          title: '进阶挑战',
          description: '提高解题能力（3星难度）',
          difficulty: 3,
          timeLimit: 900,
          questionCount: 10,
          points: 200,
          participants: 0,
          topScore: 0,
          status: 'active',
          icon: '⚡'
        },
        {
          id: 'advanced-challenge',
          title: '高级挑战',
          description: '挑战高难度题目（4-5星难度，需要方程式）',
          difficulty: 4,
          timeLimit: 1200,
          questionCount: 10,
          points: 300,
          participants: 0,
          topScore: 0,
          status: 'active',
          icon: '👑'
        },
      ];

      setChallenges(simplifiedChallenges)
    } catch (err) {
      console.error('加载挑战错误:', err)
      setError('加载挑战时发生错误')
    } finally {
      setIsLoading(false)
    }
  }

  const loadUserStats = async () => {
    try {
      // 从真实API获取用户统计
      const token = localStorage.getItem('auth_token');
      const response = await fetch('/api/challenge/stats', {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (response.ok) {
        const data = await response.json();
        setUserStats(data);
      } else {
        // 使用默认值
        setUserStats({
          totalChallenges: 0,
          completedChallenges: 0,
          totalPoints: 0,
          rank: 0,
          bestStreak: 0,
        });
      }
    } catch (err) {
      console.error('加载用户统计错误:', err);
      // 使用默认值
      setUserStats({
        totalChallenges: 0,
        completedChallenges: 0,
        totalPoints: 0,
        rank: 0,
        bestStreak: 0,
      });
    }
  }

  const startChallenge = (challenge: Challenge) => {
    if (challenge.status === 'locked') {
      alert('此挑战暂未开放')
      return
    }

    // 根据难度设置难度范围
    let difficultyRange = '1,2,3,4,5';
    if (challenge.id === 'beginner-challenge') {
      difficultyRange = '1,2';
    } else if (challenge.id === 'intermediate-challenge') {
      difficultyRange = '3';
    } else if (challenge.id === 'advanced-challenge') {
      difficultyRange = '4,5';
    }

    // 跳转到自由练习页面（不指定知识点=随机混合）
    router.push(`/practice/free`)
  }

  const getDifficultyLabel = (difficulty: number) => {
    const labels = { 1: '入门', 2: '基础', 3: '进阶', 4: '高级', 5: '竞赛' }
    return labels[difficulty as keyof typeof labels] || '未知'
  }

  const getDifficultyColor = (difficulty: number) => {
    const colors = {
      1: 'bg-green-100 text-green-800 border-green-300',
      2: 'bg-blue-100 text-blue-800 border-blue-300',
      3: 'bg-yellow-100 text-yellow-800 border-yellow-300',
      4: 'bg-orange-100 text-orange-800 border-orange-300',
      5: 'bg-red-100 text-red-800 border-red-300'
    }
    return colors[difficulty as keyof typeof colors] || 'bg-gray-100 text-gray-800 border-gray-300'
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active': return 'bg-green-100 text-green-800'
      case 'completed': return 'bg-blue-100 text-blue-800'
      case 'locked': return 'bg-gray-100 text-gray-600'
      default: return 'bg-gray-100 text-gray-800'
    }
  }

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'active': return '进行中'
      case 'completed': return '已完成'
      case 'locked': return '未开放'
      default: return '未知'
    }
  }

  const filteredChallenges = selectedDifficulty
    ? challenges.filter(c => c.difficulty === selectedDifficulty)
    : challenges

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载挑战中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900 p-6">
      <div className="max-w-7xl mx-auto">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-8 text-center"
        >
          <h1 className="text-3xl font-bold text-gray-800 dark:text-gray-200 mb-2">
            挑战模式
          </h1>
          <p className="text-gray-600 dark:text-gray-300">
            参与限时挑战，与全国学生一较高下
          </p>
        </motion.div>

        {/* 错误提示 */}
        {error && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            className="mb-6 p-4 rounded-lg bg-red-100 border border-red-300 text-red-700"
          >
            {error}
          </motion.div>
        )}

        <div className="grid lg:grid-cols-4 gap-6">
          {/* 用户统计 */}
          <div className="lg:col-span-1">
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.1 }}
            >
              <Card glassmorphism className="backdrop-blur-xl mb-6">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Trophy className="w-5 h-5" />
                    我的战绩
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {userStats && (
                    <>
                      <div className="flex items-center justify-between">
                        <span className="text-gray-600">总挑战</span>
                        <span className="font-bold text-lg">{userStats.totalChallenges}</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-gray-600">已完成</span>
                        <span className="font-bold text-lg text-green-600">{userStats.completedChallenges}</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-gray-600">总积分</span>
                        <span className="font-bold text-lg text-blue-600">{userStats.totalPoints}</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-gray-600">排名</span>
                        <span className="font-bold text-lg text-purple-600">#{userStats.rank}</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-gray-600">最佳连胜</span>
                        <span className="font-bold text-lg text-orange-600">{userStats.bestStreak}</span>
                      </div>
                    </>
                  )}
                </CardContent>
              </Card>
            </motion.div>

            {/* 难度筛选 */}
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.2 }}
            >
              <Card glassmorphism className="backdrop-blur-xl">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Target className="w-5 h-5" />
                    难度筛选
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <Button
                      variant={selectedDifficulty === null ? "default" : "outline"}
                      className="w-full justify-start"
                      onClick={() => setSelectedDifficulty(null)}
                    >
                      全部难度
                    </Button>
                    {[1, 2, 3, 4, 5].map(difficulty => (
                      <Button
                        key={difficulty}
                        variant={selectedDifficulty === difficulty ? "default" : "outline"}
                        className="w-full justify-start"
                        onClick={() => setSelectedDifficulty(difficulty)}
                      >
                        {getDifficultyLabel(difficulty)}
                      </Button>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </div>

          {/* 挑战列表 */}
          <div className="lg:col-span-3">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
              className="grid gap-6"
            >
              {filteredChallenges.length === 0 ? (
                <Card glassmorphism className="backdrop-blur-xl">
                  <CardContent className="p-12 text-center">
                    <Trophy className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                    <h3 className="text-xl font-semibold text-gray-600 mb-2">暂无挑战</h3>
                    <p className="text-gray-500">
                      {selectedDifficulty ? '没有找到符合条件的挑战' : '挑战即将开放，敬请期待'}
                    </p>
                  </CardContent>
                </Card>
              ) : (
                filteredChallenges.map((challenge, index) => (
                  <motion.div
                    key={challenge.id}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.1 * index }}
                  >
                    <Card glassmorphism className={`backdrop-blur-xl hover:shadow-lg transition-all duration-300 ${
                      challenge.status === 'locked' ? 'opacity-60' : ''
                    }`}>
                      <CardHeader>
                        <div className="flex items-start justify-between">
                          <div className="flex items-center gap-3">
                            <div className="text-3xl">{challenge.icon}</div>
                            <div>
                              <CardTitle className="text-xl text-gray-800 dark:text-gray-200">
                                {challenge.title}
                              </CardTitle>
                              <CardDescription className="mt-1">
                                {challenge.description}
                              </CardDescription>
                            </div>
                          </div>
                          <div className="flex flex-col gap-2">
                            <span className={`px-3 py-1 rounded-full text-sm font-medium ${getDifficultyColor(challenge.difficulty)}`}>
                              {getDifficultyLabel(challenge.difficulty)}
                            </span>
                            <span className={`px-3 py-1 rounded-full text-sm font-medium ${getStatusColor(challenge.status)}`}>
                              {getStatusLabel(challenge.status)}
                            </span>
                          </div>
                        </div>
                      </CardHeader>
                      <CardContent>
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                          <div className="text-center">
                            <Clock className="w-5 h-5 text-gray-500 mx-auto mb-1" />
                            <div className="text-sm text-gray-600">时间限制</div>
                            <div className="font-semibold">{Math.floor(challenge.timeLimit / 60)}分钟</div>
                          </div>
                          <div className="text-center">
                            <Target className="w-5 h-5 text-gray-500 mx-auto mb-1" />
                            <div className="text-sm text-gray-600">题目数量</div>
                            <div className="font-semibold">{challenge.questionCount}道</div>
                          </div>
                          <div className="text-center">
                            <Star className="w-5 h-5 text-gray-500 mx-auto mb-1" />
                            <div className="text-sm text-gray-600">奖励积分</div>
                            <div className="font-semibold text-blue-600">{challenge.points}分</div>
                          </div>
                          <div className="text-center">
                            <Users className="w-5 h-5 text-gray-500 mx-auto mb-1" />
                            <div className="text-sm text-gray-600">参与人数</div>
                            <div className="font-semibold">{challenge.participants}</div>
                          </div>
                        </div>

                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-4">
                            <div className="text-sm text-gray-600">
                              最高分：<span className="font-semibold text-green-600">{challenge.topScore}%</span>
                            </div>
                          </div>
                          <Button
                            onClick={() => startChallenge(challenge)}
                            disabled={challenge.status === 'locked'}
                            className={`${
                              challenge.status === 'locked'
                                ? 'bg-gray-300 cursor-not-allowed'
                                : 'bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700'
                            } text-white`}
                          >
                            {challenge.status === 'locked' ? '未开放' :
                             challenge.status === 'completed' ? '重新挑战' : '开始挑战'}
                          </Button>
                        </div>
                      </CardContent>
                    </Card>
                  </motion.div>
                ))
              )}
            </motion.div>
          </div>
        </div>
      </div>
    </div>
  )
}
